package com.dg.river.core.http.interceptor;

import com.dg.river.core.http.ApiManager;
import com.dg.river.core.util.L;
import com.dg.river.core.util.TextUtil;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * @作者：Hututu
 * @时间：2023/3/30 14:44
 * @描述：内容描述
 * @修改：修改内容
 * @Version:1.0
 */
public class LogInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        StringBuffer logContent = new StringBuffer();
        Request request = chain.request();
        // 请求地址
        String url = request.url().toString();
        // 请求方法
        String method = request.method();
        if (TextUtil.isEmptyConvert(request.url().toString()).endsWith(".apk")) {
            logContent.append(" \n----------Start----------------\n");
            logContent.append("| 请求描述：").append("开始下载文件").append("\n");
            logContent.append("| 文件下载地址：").append(url).append("\n");
            logContent.append("----------End----------\n");
            logContent.append(" \n");
            L.d(logContent.toString());
            return chain.proceed(request);
        }
        long startTime = System.currentTimeMillis();
        Response response = chain.proceed(request);
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        logContent.append(" \n----------Start----------------\n");
        if (request.tag() != null) {
            logContent.append("| 请求描述：").append(request.tag().toString()).append("\n");
        }
        // 请求结果
        int code = response.code();
        if (code == 200) {
            logContent.append("| 请求成功：").append(code).append("\n");
        } else {
            logContent.append("| 请求失败：").append(code).append("\n");
        }
        // 请求方法
        logContent.append("| 接口请求方法：").append(method).append("\n");
        // 请求地址
        logContent.append("| 接口请求地址：").append(url).append("\n");
        // 请求头
        Headers headers = request.headers();
        logContent.append("| 接口请求头：").append(headers.toString().replace("\n", ";")).append("\n");
        // 请求参数
        if ("POST".equalsIgnoreCase(method) || "DELETE".equalsIgnoreCase(method)) {
            if (!doNotLogParamAPI().contains(url)) {
                String bodyStr = "";
                RequestBody requestBody = request.body();
                if (requestBody != null) {
                    Buffer buffer = new Buffer();
                    requestBody.writeTo(buffer);
                    Charset charset = StandardCharsets.UTF_8;
                    MediaType contentType = requestBody.contentType();
                    if (contentType != null) {
                        charset = contentType.charset(StandardCharsets.UTF_8);
                    }
                    if (charset != null) {
                        bodyStr = buffer.readString(charset);
                    }
                    if (TextUtil.isEmpty(bodyStr)) {
                        logContent.append("| 接口请求参数：无参数").append("\n");
                    } else {
                        logContent.append("| 接口请求参数：").append(bodyStr).append("\n");
                    }
                }
            }
        }
        // 请求结果
        String responseContent = "";
        MediaType mediaType = null;
        if (response.body() != null) {
            responseContent = response.body().string(); // 只能调用一次，调用后数据流关闭
            mediaType = response.body().contentType();
            logContent.append("| 接口返回值：").append(responseContent).append("\n");
        }
        logContent.append("----------End:").append(duration).append("毫秒----------\n");
        logContent.append(" \n");
        L.d(logContent.toString());
        return response.newBuilder().body(okhttp3.ResponseBody.create(mediaType, responseContent)).build();
    }

    /**
     * 无需打印Param的API接口
     *
     * @return
     */
    private List<String> doNotLogParamAPI() {
        List<String> data = new ArrayList<>();
        data.add(ApiManager.Other.POST_UPLOAD_FILE);
        return data;
    }
}
